<?php
/**
 * 工具类
 * User: liuser
 * Date: 2018/4/8
 * Time: 下午5:52
 */
class util
{
    public static $useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36';
    public static $referer = 'http://top.baidu.com/buzz?b=341&c=513&fr=topbuzz_b1';

    public static function curl($url,$cookie="")
    {

        $useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36';
        //初始化
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
        curl_setopt($curl,CURLOPT_TIMEOUT,30);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt ( $curl, CURLOPT_HTTPPROXYTUNNEL, false );
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
        #设置代理
//        curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:1086');		// 代理本地ip:端口
//        curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);	// socks5

        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);

        }
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
//        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        $error = curl_error($curl);
        //关闭URL请求
        curl_close($curl);
        if(!empty($error)){
            return false;
        }
        return $data;
    }
    public static function save_to_file($filename,$url)
    {
        $hander = curl_init();
        curl_setopt($hander, CURLOPT_USERAGENT, self::$useragent);
        curl_setopt($hander, CURLOPT_REFERER, self::$referer);
        $fp = fopen($filename,'wb');
        curl_setopt($hander,CURLOPT_URL,$url);
        curl_setopt($hander,CURLOPT_FILE,$fp);
        curl_setopt($hander,CURLOPT_HEADER,0);
        curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
        //curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
        curl_setopt($hander,CURLOPT_TIMEOUT,60);
        $output = curl_exec($hander);
        $error = curl_error($hander);
        curl_close($hander);
        fclose($fp);
        return $error;
    }
}